﻿using QDAS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QDasConverter.Core
{
    public class C2021T11_TDMS : ConvertBase
    {
        /// <summary>
        /// 数据目录。
        /// </summary>
        public string DataDirectory = @"C:\data\Kisler.DIFF0030";

        public string BackupDirectory = @"C:\data\Kisler.DIFF0030.Backups";

        // 配置文件
        public string ConfigFile = @"configs\C2021T11_TDMS_pathlist.txt";

        public C2021T11_TDMS()
        {
            DisplayName = "霍塔TDMS模块";
            Version = "V1.0 Released Date: 2021/01/14 Inner Name: C2021T11_TDMS";
        }

        public override void Initialize()
        {
            base.Initialize();
            NeedConnectionCheck = false;
            ConvertInterval = 3;
            // DataDirectory = ia.ReadString("DataPath", DataDirectory);
        }

        public override bool OnStart()
        {
            if (DebugMode)
            {
                Console.WriteLine("Debug Mode");
            }

            return base.OnStart();
        }


        // 需要一直转换。
        public override bool NeedConvert() => true;

        bool debug = false;
        public override void OneLoop_Process()
        {
            // 正式运行
            if (!debug)
            {
                ConfigFile = Path.GetFullPath(ConfigFile);
                if (!File.Exists(ConfigFile))
                    return;

                foreach (var dir in File.ReadAllLines(ConfigFile))
                {
                    if (!Directory.Exists(dir))
                        continue;

                    foreach (var tdmsfile in Directory.GetFiles(dir))
                    {
                        try
                        {
                            // 只对 .tdms 后缀的文件进行转换。
                            if (tdmsfile.ToLower().EndsWith(".tdms"))
                                ProcessTDMS(tdmsfile);
                        }
                        catch { }
                    }
                } 
            }
            // 测试模式
            else
            {
                DataDirectory = @"C:\Users\hao\source\repos\tsingshan-converter\TdmsDemo\data";
                foreach (var tdmsfile in Directory.GetFiles(DataDirectory))
                {
                    try
                    {
                        // 只对 .tdms 后缀的文件进行转换。
                        if (tdmsfile.ToLower().EndsWith(".tdms"))
                            ProcessTDMS(tdmsfile);
                    }
                    catch { }
                }
            }

        }

        /// <summary>
        /// 对每个文件进行处理，将处理好的数据保存为DFQ
        /// </summary>
        /// <param name="tdmsfile"></param>
        private void ProcessTDMS(string tdmsfile)
        {
            // tdms 有两块内容：Groups 和 Properties， 分别包括数据层和零件层信息
            var tdms = new NationalInstruments.Tdms.File(tdmsfile);
            tdms.Open();

            // 1. 从 tdms.Properties 获得的零件层信息 
            var K1001 = tdms.Properties["Model"];
            var K0004 = DateTime.Parse(tdms.Properties["datetime"].ToString());
            var K0010 = tdms.Properties["Operate_Type"];
            var K0012 = tdms.Properties["Operate_Type"];
            var K0014 = tdms.Properties["SerialNum"];

            // 2. 提取参数信息
            Dictionary<string, QCh> qchs = new Dictionary<string, QCh>(); // 记录提取到的零件层信息
            var group0 = tdms.Groups["TestItems"];
            foreach (var ch in group0.Channels)
            {
                QCh qCh = new QCh();
                qCh.Key = ch.Key;
                foreach (var p in ch.Value.Properties)
                {
                    switch (p.Key)
                    {
                        case "Disaplay": qCh.K2001 = p.Value.ToString(); break;
                        case "Precision": qCh.K2022 = p.Value.ToString(); break;
                        case "PhyiscalUnit": qCh.K2142 = p.Value.ToString(); break;
                        default: break;
                    }
                }

                qchs.Add(ch.Key, qCh);
            }


            // 3. 从 tdms.Group[1] 开始，每个Group包括了大量的一个测量值，测量值会保存在 qchs.values 中
            foreach (var group in tdms.Groups)
            {
                if (group.Key == "TestItems")
                    continue;

                foreach (var ch in group.Value.Channels)
                {
                    // ch.Key的格式为P1001，一般来说肯定存在于字典中，加入验证保证不出错
                    if (!qchs.ContainsKey(ch.Key))
                        continue;

                    // 添加至对应集合的数据列表中。
                    var list = qchs[ch.Key].values;
                    foreach (var v in ch.Value.GetData<double>())
                        list.Add(v.ToString());
                }

                // 暂时只输出一组数据用于测试
                break;
            }

            QFile qf = new QFile();
            qf[1001] = K1001;
            qf[1002] = K1001;
            qf[1203] = "输入电机驱动扭矩曲线";
            qf[1206] = "蒂森检测台";

            foreach (var ch in qchs.Values)
            {
                if (ch.values.Count == 0)
                    continue;

                var qc = qf.AddQCharacteristic();
                qc[2001] = ch.Key;
                qc[2002] = ch.K2001;
                qc[2022] = ch.K2022;
                qc[2142] = ch.K2142;

                foreach (var v in ch.values)
                {
                    var qd = qc.AddItem();
                    qd.SetValue(v.ToString());
                    qd.date = K0004;
                    qd[0010] = K0010;
                    qd[0012] = K0012;
                    qd[0014] = K0014;
                }

                qf.ToDMode();
                SaveToDFQ(qf, OutputDirectory, $"C11_TDMS_{K1001}_{DateTime.Now:yyyyMMddHHmmss}.dfq");
            }

            CopyFileTo(tdmsfile, BackupDirectory, true);
        }


        class QCh
        {
            public string Key = "";
            public string K2001 = "";
            public string K2022 = "";
            public string K2142 = "";
            public List<string> values = new List<string>();
            public override string ToString() => $"{Key}: {K2001}({K2022}, {K2142}), Data Count={values.Count}";
        }
    }
}
